<template>
	<!-- <div class="scale-wrapper" ref="scrollContainer" 	> -->
		<div class="content scale-content"
		:style="{
		
			transition: isDragging ? 'none' : 'transform 0s'
		}">
		<!-- width: imgWidth  + 'px', // 动态计算内容宽度 -->
<!-- height: imgHeight+ 'px', // 动态计算内容高度 -->
		<!-- height: imgHeight>scaledHeight?scaledHeight:imgHeight + 'px', // 动态计算内容高度 -->
		<!-- width: imgWidth>scaledWidth?scaledWidth:imgWidth  + 'px', // 动态计算内容宽度 -->
			<!-- height:scaledHeight, -->
			<!-- width:scaledWidth, -->

		<!-- <div style="position: relative;"
		v-loading="loading"
		:style="{
			width: imgWidth  + 'px', // 动态计算内容宽度
			height: imgHeight+ 'px', // 动态计算内容高度
		}"
		> -->
		
			<img :src="currentImage?currentImage.imageUrl:''" ref="imgs" @load="handleImageLoad" 
		v-loading="loading"
			:style="{
				transformOrigin: 'center center', // 确保从左上角开始缩放
				transform: `rotate(${rotateAngle}deg) 
				translate(${
				rotateAngle==90?
				(imgHeight-imgWidth)/2:(rotateAngle==270?
				(imgWidth-imgHeight)/2:(rotateAngle==-90?
				-(imgHeight-imgWidth)/2:(rotateAngle==-270?
				-(imgWidth-imgHeight)/2:0)))
				}px, 
				${
				rotateAngle==90?
				(imgHeight-imgWidth)/2:(rotateAngle==270?
				(imgWidth-imgHeight)/2:(rotateAngle==-90?
				-(imgHeight-imgWidth)/2:(rotateAngle==-270?
				-(imgWidth-imgHeight)/2:0)
					)
					)
				}px)`,

				position: 'absolute',
			transformOrigin: 'center', // 确保从左上角开始缩放
				left: '0%',
				top: '0%'
			}"
			>
			<img/>
			<div 
		v-loading="loading"
			:style="{
				position: 'absolute',
			width: imgWidth  + 'px', // 动态计算内容宽度
			height: imgHeight+ 'px', // 动态计算内容高度
		}"></div>
			<canvas ref="markCanvas" tabindex='0'
		v-loading="loading"
			:style="{
				position: 'absolute',
						cursor: isDragging ? 'grabbing !important' : 'grab !important',
			}"
			></canvas>
		</div>
		<!-- </div> -->
</template>
<script>
import { mapState } from 'vuex';
import { draw, getJudge, delDraw } from "@/utils/drawCropperW"; // 矩形绘制方法
export default {
	name: 'marks',
	props: ['imageUrllist', 'parentData', 'modelarealistcavans', 'pagevale', 'drawStatus', 'scale',
		'isDragging',
'startX',
'startY',
'offsetX',
'offsetY',
'rotateAngle',
'drawLoading'
	],
	data() {
		return {
			activeMark:{},
			markList: [
				
			], // 标记内容数组
			isDrawing: false,
			questiontype: '',
			currentIndex: 0, // 当前图片索引
			currentImage: {},
			images: [],
			value: '第1张',
			imgWidth: '',
			imgHeight: '',
			containerHeight:'',
			lastClickTime: 0,
			clickDelay: 300,
			defaultTemplatePointType: null,
			loading: false
		}
	},
	watch: {
		drawLoading(val, oval) {
			this.loading = val;
		},

		markList: function (val, oval) {
			this.$emit('updateMarkList', val);
		},
		modelarealistcavans: {
			handler(val, ova) {
				this.markList = val
				setTimeout(() => {
					this.initCanvas(2); // 画布初始化
				}, 1000)
			},
			deep: true
		},
		pagevale(val, oval) {
			this.currentImage = this.images[val - 1]; // 更新当前图片
		},
		imageUrllist: {
			handler(val, ova) {
				this.images = val
				this.currentImage = val[this.pagevale - 1]; // 初始化当前图片
			},
			deep: true
		},
		drawStatus: {
			immediate: true,
			deep: true, // 添加深度监听
			handler(val, ova) {
				// if (val) {
					if (val !== this.isDrawing) {
					// 进入绘制模式
						this.isDrawing = val;
						this.handleDrawStatusChange(val);
					}else{
					// 退出时恢复默认拖拽状态
					this.isDragging = false;

					}
				// } else {
				// }
			}
		},
		isDrawing:{
			immediate: true,
			deep: true, // 添加深度监听
			handler(val, ova) {
				this.$emit('isDrawingChange', val)
			}
		},
		rotateAngle:{
			immediate: false,
			deep: true, // 添加深度监听
			handler(val, ova) {
				let width = this.imgWidth;
				let height = this.imgHeight;
					this.imgWidth = height;
					this.imgHeight = width;
				this.initCanvas()
				// this.$emit('rotateAngleChange', val)
			}
		}
	},
	created() {
	},
	 mounted() {
		this.currentImage = this.imageUrllist[this.currentIndex]; // 初始化当前图片
		 this.handleImageLoad()
		// setTimeout(()=>{
		// 	this.initCanvas(1); // 画布初始化
		// },100)
		document.addEventListener('customMouseDown', (event) => {
			// //console.log(event);
		});
	},
	components: {},
	computed: {
		...mapState(['circleselectionstatus']), // 从 Vuex 中获取状态
		scaledWidth() {
			this.$nextTick()
			return this.imgWidth * (this.scale / 100)
		},
		scaledHeight() {
			this.$nextTick()
			return this.imgHeight * (this.scale / 100)
		},
		
	},
	methods: {
		
		getDraggableElement() {
			return this.$refs.draggableElement;
		},
		modeltypetab(val) {
			this.isDrawing = true;
			this.$emit('modeltype', val);
			// 设置默认的templatePointType
			this.defaultTemplatePointType = val; // 保存当前选择的类型
			this.startCrop();
		},
		startCrop() {
			let cav = this.$refs.markCanvas;
			// 在创建新区域时使用保存的类型
			const newArea = {
				templatePointType: this.defaultTemplatePointType, // 使用选择的类型
				// ... 其他属性
			};
			// draw(cav, this.modelarealistcavans, undefined, this.isDrawing);
			draw(cav, this.modelarealistcavans, undefined, that.isDrawing, (newRectangle) => {
				// 处理新矩形对象
				this.handleNewRectangle(newRectangle);
			});
		},
		handleImageLoad() {
			const img = this.$refs.imgs;
			const canvas = this.$refs.markCanvas;

			// 设置 canvas 宽高与图片一致
			canvas.width = img.naturalWidth;  // 图片原始宽度
			canvas.height = img.naturalHeight; // 图片原始高度

			// 如果需要设置样式宽高（CSS 控制显示大小）
			this.imgWidth = `${img.naturalWidth}`;
			this.imgHeight = `${img.naturalHeight}`;

			this.initCanvas()
		},
		/* 画布初始化 */
		initCanvas(num) {
			this.loading = false;
			// if (this.isDrawing) {
			// 	return false
			// }
			let that = this
			this.$nextTick(() => {
				// 初始化canvas宽高
				let cav = that.$refs.markCanvas;
				let ctx = cav.getContext('2d');
				ctx.strokeStyle = '#295CFF'
				cav.style.cursor = 'crosshair'
				const img = that.$refs.imgs;
				console.log(that.imgHeight,'img.naturalHeight');
				
				if (num == 1) {
					img.onload = () => {

						cav.width = that.imgWidth;
						cav.height =  that.imgHeight;
						// cav.width = img.naturalWidth;
						// cav.height = img.naturalHeight;
						// that.imgHeight = img.naturalHeight;
						// that.imgWidth = img.naturalWidth;
						// 计算使用变量
						let list = that.markList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
						// console.info('newlist', list)
						// 若list长度不为0, 则显示已标记框
						if (list.length !== 0) {
							// //console.info('dddddd')
							list.forEach(function (value, index, array) {
								ctx.clearRect(value.x, value.y, value.width, value.height);
								// 遍历绘制所有标记框
								ctx.beginPath();
								ctx.strokeStyle = '#295CFF';
								ctx.fillStyle = 'RGBA(102,102,102,0.2)'; // 设置背景颜色为蓝色
								ctx.rect(value.x, value.y, value.width, value.height);
								ctx.stroke();
								// 添加透明背景
								ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
								ctx.fillRect(value.x, value.y, value.width, value.height); // 填充矩形

								if (value.options && value.options.length > 0) {
									// //console.info(value.options.length);
									value.options.forEach(option => {
										ctx.beginPath();
										ctx.fillStyle = 'rgba(255, 0, 0, 0.2)'; // 透明度0.2
        								ctx.fillRect(option.x, option.y, option.width, option.height);
										ctx.strokeStyle = 'red';  // 设置边框颜色为红色
										ctx.rect(option.x, option.y, option.width, option.height);
										ctx.stroke();
									});
								}

								// 新增题型显示 - 统一样式
								const typeButtonWidth = 80;
								const typeButtonHeight = 24;

								// 绘制文字背景 - 贴着矩形框顶部
								ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
								ctx.fillRect(value.x, value.y - typeButtonHeight, typeButtonWidth, typeButtonHeight);

								// 设置文字样式
								ctx.fillStyle = '#1A48DB';
								ctx.font = '14px Microsoft YaHei';
								ctx.textAlign = 'center';
								ctx.textBaseline = 'middle';

								// 根据templatePointType显示不同内容
								let typeText = value.templatePointType;
								// 绘制文字 - 调整文字垂直位置，确保居中
								ctx.fillText(typeText + name, value.x + typeButtonWidth / 2, value.y - typeButtonHeight / 2);


							});
						}
						cav.addEventListener('click', function (event) {
							const rect = cav.getBoundingClientRect();
							const x = event.clientX - rect.left;
							const y = event.clientY - rect.top;
							that.handleCanvasClick(x, y);
						});
						// 调用封装的绘制方法
						//   draw(cav, list,undefined, this.isDrawing);
						draw(cav, list, undefined, that.isDrawing, (newRectangle) => {
							// 处理新矩形对象
							that.handleNewRectangle(newRectangle);
						});
					}
				} else {
					cav.width = that.imgWidth;
						cav.height =  that.imgHeight;
					// cav.width = img.naturalWidth;
					// cav.height = img.naturalHeight;
					// that.imgHeight = img.naturalHeight;
					// that.imgWidth = img.naturalWidth;
					// 计算使用变量
					let list = that.markList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
					// console.info('newlist', list)
					// 若list长度不为0, 则显示已标记框
					if (list.length !== 0) {
						// //console.info('dddddd')
						list.forEach(function (value, index, array) {
							// console.info('marklist', value)
							ctx.clearRect(value.x, value.y, value.width, value.height);
							// 遍历绘制所有标记框
							ctx.beginPath();
							ctx.strokeStyle = '#295CFF';
							ctx.rect(value.x, value.y, value.width, value.height);
							ctx.stroke();
							// 添加透明背景
							ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
							ctx.fillRect(value.x, value.y, value.width, value.height); // 填充矩形
							if (value.options && value.options.length > 0) {
								// //console.info(value.options.length);
								value.options.forEach(option => {
									ctx.beginPath();
									ctx.fillStyle = 'rgba(255, 0, 0, 0.2)'; // 透明度0.2
									ctx.fillRect(option.x, option.y, option.width, option.height);
									ctx.strokeStyle = 'red';  // 设置边框颜色为红色
									ctx.rect(option.x, option.y, option.width, option.height);
									ctx.stroke();
								});
							}

							// 新增题型显示 - 统一样式
							const typeButtonWidth = 80;
							const typeButtonHeight = 24;

							// 绘制文字背景 - 贴着矩形框顶部
							ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
							ctx.fillRect(value.x, value.y - typeButtonHeight, typeButtonWidth, typeButtonHeight);

							// 设置文字样式
							ctx.fillStyle = '#1A48DB';
							ctx.font = '14px Microsoft YaHei';
							ctx.textAlign = 'center';
							ctx.textBaseline = 'middle';

							// 根据templatePointType显示不同内容
							let typeText = value.templatePointType;
							// 绘制文字 - 调整文字垂直位置，确保居中
							ctx.fillText(typeText + name, value.x + typeButtonWidth / 2, value.y - typeButtonHeight / 2);


						});
					}
					cav.addEventListener('click', function (event) {
						const rect = cav.getBoundingClientRect();
						const x = event.clientX - rect.left;
						const y = event.clientY - rect.top;
						that.handleCanvasClick(x, y);
					});
					// //console.info(list)
					// 调用封装的绘制方法
					// draw(cav, list,undefined, this.isDrawing);
					draw(cav, list, undefined, that.isDrawing, (newRectangle) => {
						// 处理新矩形对象
						that.handleNewRectangle(newRectangle);
					});


				}
			})

		},
		// 计算按钮位置
		getButtonPositions(mark) {
			const buttonWidth = 60;
			const buttonHeight = 20;
			const buttonMargin = 5;

			const editButtonX = mark.x + mark.width - buttonWidth - buttonMargin;
			const editButtonY = mark.y + mark.height + buttonMargin;
			const deleteButtonX = editButtonX - buttonWidth - buttonMargin;
			const deleteButtonY = editButtonY;

			return {
				edit: {
					x: editButtonX,
					y: editButtonY,
					width: buttonWidth,
					height: buttonHeight
				},
				delete: {
					x: deleteButtonX,
					y: deleteButtonY,
					width: buttonWidth,
					height: buttonHeight
				}
			};
		},

		// 检查点击是否在按钮区域内
		isClickInButton(x, y, button) {
			return x > button.x &&
				x < button.x + button.width &&
				y > button.y &&
				y < button.y + button.height;
		},

		// 处理画布点击
		handleCanvasClick(x, y) {
			// 检查点击时间间隔
			const now = Date.now();
			if (now - this.lastClickTime < this.clickDelay) {
				return;
			}
			this.lastClickTime = now;
			if (this.isProcessing) return;
			this.isDrawing = false;
			this.$emit('cancasClick',this.pagevale)
			// 判断点击是否在矩形框内
				let cav = this.$refs.markCanvas;
				let ctx = cav.getContext('2d');
			this.markList.slice().reverse().forEach((mark, originalIndex) => {
				const index = this.markList.length - 1 - originalIndex;
				const startX = Math.min(mark.x, mark.x + mark.width);
				const endX = Math.max(mark.x, mark.x + mark.width);
				const startY = Math.min(mark.y, mark.y + mark.height);
				const endY = Math.max(mark.y, mark.y + mark.height);

				if (x > startX && x < endX && 
					y > startY && y < endY) {
						this.$nextTick(()=>{
							ctx.beginPath();
							// 动态设置边框颜色
							ctx.strokeStyle = this.activeMark.index === index ? '#FF0000' : '#295CFF';
							ctx.rect(this.activeMark.x, this.activeMark.y, this.activeMark.width, this.activeMark.height);
							ctx.stroke();
						})
					// console.log('点击有效选框');
					// console.log('点击第', index + 1, '层选框',originalIndex);
					this.activeMark = {index, ...mark};
					return true;
				}
			});
		
			
		},

		// 处理编辑
		handleEdit(mark) {
			// 防止重复处理
			if (this.isProcessing) return;

			try {
				this.isProcessing = true;
				let obj = { ishow: true }
				const mergedObj = Object.assign({}, obj, mark);
				this.$emit('editContent', mergedObj)
				//console.info('编辑按钮被点击', mark); // 添加mark信息以便调试
				// 这里添加你的编辑逻辑
			} finally {
				this.isProcessing = false;
			}
		},

		// 处理删除
		async handleMarkDelete(mark, index) {
			try {
				this.isProcessing = true;

				if (mark.id) {
					// 删除服务器数据
					await this.deleteFromServer(mark.id);
				} else {
					// 删除本地数据
					this.deleteLocal(index);
				}
			} finally {
				this.isProcessing = false;
			}
		},

		// 从服务器删除
		async deleteFromServer(id) {
			try {
				const res = await dele('/template/cuttingregion/delete',
					{ id },
					{
						headers: {
							'Content-Type': 'x-www-form-urlencoded',
						}
					}
				);

				if (res.code === 200) {
					this.$message.success('删除成功');
					this.$emit('refreshdata');
				} else {
					throw new Error(res.message || '删除失败');
				}
			} catch (error) {
				console.error('Delete error:', error);
				this.$message.error(error.message || '删除失败');
				throw error;
			}
		},

		// 本地删除
		deleteLocal(index) {
			this.markList.splice(index, 1);
			this.$message.success('删除成功');
		},
		handleNewRectangle(newRectangle) {
			this.$emit('newRectangle', newRectangle);
		},
		handleDrawStatusChange(val) {
			if (val) {
				let cav = this.$refs.markCanvas;
				// 添加画布边界监听
      			cav.addEventListener('mouseleave', this.handleCanvasLeave);
				if (cav) {
					draw(cav, this.modelarealistcavans, undefined, val, (newRectangle) => {
						this.handleNewRectangle(newRectangle);
						// 绘制完成后重置状态
						this.isDrawing = false;
						// this.$emit('update:drawStatus', false);
					});
				}else{

				}
			}else{
				this.isDrawing = false;
			}
		},
		handleCanvasLeave() {
			console.log('选框超出边界');
			this.$emit('cancasClick',this.pagevale)
			this.isDrawing = false;
		}
	},
	beforeDestroy() {
		// 移除事件监听器
		document.removeEventListener('customMouseDown', (event) => { })
	}
}
</script>
<style lang='scss' scoped>
.content {
	position: relative;
}

img {
	position: absolute;
	top: 0;
	left: 0;
	object-fit: contain;
	z-index: 9;
}

canvas {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 10;
}

.routate {
	position: fixed;
	left: 25px;
	top: 110px;
	background: #fff;
	height: 60px;
	display: flex;
	align-items: center;
	padding: 0 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
	border-radius: 5px;
	font-size: 14px;
	color: #557292;
	border-radius: 10px;
	z-index: 111;
	/* transform: translateX(-50%); */
}

.el-select,
.el-input {
	width: 100px;
}

.el-select {
	margin-right: 10px;
	margin-left: 10px;
}

.el-input {
	margin-left: 10px;
	margin-right: 10px;
}

.routate>>>.el-button {
	border-radius: 10px;
	height: 35px;
	padding: 0 10px;
}

.routate>>>.el-input__inner {
	border-radius: 10px;
	height: 35px;
}
.scale-wrapper {
  overflow: hidden;
//   width: 100vw;
	// height:calc(100vh - 102px);
  position: relative;
}

.scale-content {
  transition: transform 0.3s ease;
  will-change: transform;
}
</style>